<?php

namespace App\Http\Controllers\Api\V1\Frontend;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Api\V1\Order\CreateRequest;
use App\Models\Order\Item;
use App\Models\Order\Order;
use App\Models\Video;
use App\Models\Wechat;
use App\Transformers\Frontend\OrderTransformer;
use App\Tyt\Manager\Wechat\WechatManager;
use function EasyWeChat\Kernel\Support\generate_sign;

class OrderController extends BaseController
{
    public function index()
    {
        $orders = Order::where('author_id', \Auth::user()->id)->where(function ($query) {
            if ($state = request()->get('state', '')) {
                $query->where('state', $state);
            }
        })->paginate(15);
        return $this->response->paginator($orders, new OrderTransformer());
    }

    public function store(CreateRequest $request)
    {
        $model = \DB::transaction(function () use ($request) {
            $attributes = $request->validated();
            $video = Video::find($attributes['video_id']);
            $attributes['number'] = 'TYT' . date('Ymd') . random_int(1, 1000);
            $attributes['author_id'] = \Auth::user()->id;
            $attributes['total'] = $video->price;
            $attributes['state'] = Order::ORDER_NEW;
            $order = Order::create($attributes);
            $item = new Item();
            $item->order_id = $order->id;
            $item->video_id = $attributes['video_id'];
            $item->author_id = $order->author_id;
            $item->item_total = $video->price;
            $item->save();
            return $order;
        });
        $config = Wechat::first();
        $wechat = new WechatManager($config);
        $wechat->payment();
        $result = $wechat->unify($model);
        if ($result['return_code'] === 'SUCCESS') {
            // 二次签名的参数必须与下面相同
            $params = [
                'appId'     => $result['appid'],
                'timeStamp' => time(),
                'nonceStr'  => $result['nonce_str'],
                'package'   => 'prepay_id=' . $result['prepay_id'],
                'signType'  => 'MD5',
            ];

            $params['paySign'] = generate_sign($params, $config->mch_key);

            return ['data' => $params];
        } else {
            return $result;
        }
    }

    public function payment()
    {
        $model = Order::find(request()->get('video_id', ''));
        $config = Wechat::first();
        $wechat = new WechatManager($config);
        $wechat->payment();
        $result = $wechat->unify($model);
        if ($result['return_code'] === 'SUCCESS') {
            // 二次签名的参数必须与下面相同
            $params = [
                'appId'     => $result['appid'],
                'timeStamp' => time(),
                'nonceStr'  => $result['nonce_str'],
                'package'   => 'prepay_id=' . $result['prepay_id'],
                'signType'  => 'MD5',
            ];

            $params['paySign'] = generate_sign($params, $config->mch_key);

            return ['data' => $params];
        } else {
            return $result;
        }
    }
}